<template>
  <div>
    <top-nav-bar :applyPageRoute="$route.meta.title" @back="$router.go(-1)"></top-nav-bar>
    <a-card :bordered="false">
      <select-student @getStudent="studentInfos" :projectType="2"/>
    </a-card>
    <a-card :bordered="false" style="margin-top:8px;">
      <div v-if="studentInfo.id">
        <div class="title">退物品信息</div>
        <div style="display:flex">
          <div style="margin-right:15px;">
            <span>校区信息：</span>
            <span>
              <a-select
                style="width: 200px"
                placeholder="请选择校区"
                v-model="structures_id"
                @change="getReturnCourse"
                :disabled="this.course_id==undefined?false:true"
                allowClear
              >
                <a-select-option
                  v-for="(item,index) in studentInfo.couserInfo.structures_ids"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </span>
          </div>
          <div v-if="structures_id">
            <span>退出物品：</span>
            <span>
              <a-select
                style="width: 200px"
                placeholder="请选择退出的物品"
                @change="getOrder"
                v-model="course_id"
                allowClear
              >
                <a-select-option
                  v-for="(item,index) in courseList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </span>
          </div>
        </div>
        <div v-if="course_id&&orderArr.length>0&&isArrears==1" style="margin-top:15px;">
          <a-table
            :columns="orderColumns"
            :data-source="orderArr"
            :pagination="false"
            class="user_management_table"
            style="border:1px solid #e8e8e8"
          >
            <!-- 表格头部插入 -->
            <span slot="customTitle">
              单价
              <a-tooltip>
                <template slot="title">单价=（总价-优惠金额-优惠券抵扣-赠送金额抵扣）/购买数量</template>
                <a-icon type="question-circle" theme="filled" style="color: #bfbfbf; margin-left: 5px" />
              </a-tooltip>
            </span>
            <span slot="lossTitle">
              手续费/亏损费
              <a-tooltip>
                <template slot="title">
                  <div style="margin-bottom:10px;">手续费：指机构根据规定在退转课时收取学员额外的费用。当退转出金额少于应退转出金额时，将产生手续费。</div>
                  <div>亏损费：指机构在退转课时支付退课额外的费用。当退转出金额超过应退转出金额时，将产生亏损费。</div>
                </template>
                <a-icon type="question-circle" theme="filled" style="color: #bfbfbf; margin-left: 5px" />
              </a-tooltip>
            </span>
            <span slot="order_no" slot-scope="text,record">
              <a @click="openOrderModel(record)">{{record.order.order_no}}</a>
            </span>
            <span slot="unit_price" slot-scope="text,record">
              {{record.unit_price}}元/件
            </span>
            <!-- 数量 -->
            <span slot="surplus_buy_number" slot-scope="text,record">
              {{record.surplus_buy_number}}件
            </span>
            <!-- 剩余金额 -->
            
            <span slot="returnBuyNumber" slot-scope="text,record,index">
              <a-input-number
                style="margin-right:5px;"
                :min="0"
                :max="record.surplus_buy_number"
                v-model="record.returnBuyNumber"
                @change="changeReturnBuyNumber($event,record,index)"
              />件
            </span>

            <!-- <span slot="returnGiveNumber" slot-scope="text,record,index">
              <a-input-number
                style="margin-right:5px;"
                :min="0"
                :max="record.surplus_give_number"
                v-model="record.returnGiveNumber"
                @change="changeReturnGiveNumber($event,record,index)"
              />课时
            </span>-->
            <span
              slot="surplusMoney"
              slot-scope="text,record"
            >￥{{record.unit_price*record.surplus_buy_number}}</span>

            <span slot="returnMoney" slot-scope="text,record,index">
              ￥
              <a-input-number
                :min="0"
                v-model="record.returnMoney"
                @change="changeReturnMoney($event,record,index)"
              />
            </span>
            <span slot="is_return_warehouse" slot-scope="text,record">
              <a-checkbox @change="returnWareHouse($event,record)" />
            </span>
            <span slot="lossMoney" slot-scope="text,record">
              <div v-if="record.serviceSumMoney">
                <div v-if="record.serviceSumMoney-record.serviceMoney==0">￥0.00</div>
                <div v-if="record.serviceSumMoney-record.serviceMoney>0">
                  <div
                    style="color: rgb(42, 194, 80);"
                  >￥{{record.serviceSumMoney-record.serviceMoney}}</div>
                  <div>（手续费）</div>
                </div>
                <div v-if="record.serviceSumMoney-record.serviceMoney<0">
                  <div
                    style="color: rgb(255, 79, 79);"
                  >￥{{Math.abs(record.serviceSumMoney-record.serviceMoney)}}</div>
                  <div>（亏损费）</div>
                </div>
              </div>
              <div v-else>
                <div v-if="record.surplus_buy_number*record.unit_price-record.returnMoney==0">￥0.00</div>
                <div v-if="record.surplus_buy_number*record.unit_price-record.returnMoney>0">
                  <div
                    style="color: rgb(42, 194, 80);"
                  >￥{{record.surplus_buy_number*record.unit_price-record.returnMoney}}</div>
                  <div>（手续费）</div>
                </div>
                <div v-if="record.surplus_buy_number*record.unit_price-record.returnMoney<0">
                  <div
                    style="color: rgb(255, 79, 79);"
                  >￥{{Math.abs(record.surplus_buy_number*record.unit_price-record.returnMoney)}}</div>
                  <div>（亏损费）</div>
                </div>
              </div>
            </span>
            <span slot="action" slot-scope="text,record,index">
              <!-- <a @click="remove(index)">移除</a> -->
              <a-checkbox @change="remove($event,record,index)" :defaultChecked="true" />
            </span>
          </a-table>
          <div style="text-align:right;margin-top:8px;">
            应退金额：
            <span class="sum-money">￥{{returnSumMoney}}</span>
          </div>
        </div>
        <div v-if="course_id&&orderArr.length>0&&isArrears==2" style="margin-top:15px;">
          <a-alert message="此物品存在欠费，为了准确对账，请先补交欠费订单后再退物品。" banner style="margin:10px 0;" />
          <div v-for="(item,index) in orderArr" :key="index" class="mb10">
            欠费订单：{{item.order_no}}（欠费¥{{item.price}}）
            <a @click="afterPayMent(item)">去补交></a>
          </div>
        </div>
      </div>
      <div class="empty-form" v-else>
        <img src="~@/assets/img/search.png" />
        <div>请点击从左上角按钮搜索学员</div>
      </div>
    </a-card>
    <a-card
      :bordered="false"
      style="margin-top:8px;"
      v-if="course_id&&orderArr.length>0&&isArrears==1"
    >
      <div class="headertitle">支付信息</div>
      <div class="pay-way">
        <p class="title">应退金额：￥{{returnSumMoney}}</p>
        <div class="refund-list">
          <span>退款方式：</span>
          <div
            class="refund-item"
            :class="{active:courrent==index?true:false}"
            v-for="(item,index) in  btnStyle"
            :key="index"
            @click="handerPayWay(item,index)"
          >
            <a-icon
              :type="item.icon"
              :style="{color:item.color,'margin-right':'10px','font-size':'15px'}"
            ></a-icon>
            <span>{{item.text}}</span>
          </div>
        </div>
      </div>
    </a-card>
    <a-card :bordered="false" style="margin-top:8px;margin-bottom:65px;">
      <transfer-info ref="otherInfo" />
    </a-card>
    <div class="footer">
      <a-button style="margin-right:8px;">取消</a-button>
      <a-button type="primary" @click="finishReturnCourse">确认退物品</a-button>
    </div>
    <order-model ref="orderModel" />
    <after-pay ref="afterPay" @update="update" />
  </div>
</template>

<script>
import moment from 'moment'
import topNavBar from '@/components/topNavBar/topNavBar'
import selectStudent from '@/components/SelectStudent'
import orderModel from '@/components/returnOrderModel'
import afterPay from '@/components/afterPay'

import transferInfo from '@/components/transferiInfo'
import { studentGoods, studentCourseList, createReturnCourse,lookStructures } from '@/api/returnInfo'
export default {
  components: {
    topNavBar,
    selectStudent,
    transferInfo,
    orderModel,
    afterPay,
  },
  data() {
    return {
      form: {
        school_id: this.$store.state.user.school,
        refund_method: 1,
        project_type: 2,
        order_arr: [],
      },
      btnStyle: [
        {
          type: 1,
          text: '支付宝',
          color: '#1890ff',
          icon: 'alipay-circle',
          check: false,
          price: 0,
        },
        {
          type: 2,
          text: '微信',
          color: '#52c42a',
          icon: 'wechat',
          check: false,
          price: 0,
        },
        {
          type: 3,
          text: '现金',
          color: '#FF7F24',
          icon: 'transaction',
          theme: 'filled',
          check: false,
          price: 0,
        },
        {
          type: 4,
          text: '网银转账',
          color: '#1296db',
          icon: 'global',
          check: false,
          price: 0,
        },
        {
          type: 5,
          text: 'POS机刷卡',
          color: '#39d63e',
          icon: 'credit-card',
          check: false,
          price: 0,
        },
      ],
      courrent: 0,
      studentInfo: {
        couserInfo: {
          structures_ids: [],
        },
      },
      structures_id: undefined,
      courseList: [],
      course_id: undefined,
      isArrears: 0, //是否有欠费订单
      orderArr: [],
      orderColumns: [
        {
          title: '订单号',
          dataIndex: 'order_no',
          scopedSlots: { customRender: 'order_no' },
        },
        {
          slots: { title: 'customTitle' },
          // dataIndex: 'unit_price',
          scopedSlots: { customRender: 'unit_price' },
        },
        {
          title: '可退数量',
          // dataIndex: 'surplus_buy_number',
          scopedSlots: { customRender: 'surplus_buy_number' },
        },
        // {
        //   title: '剩余赠送数量',
        //   dataIndex: 'surplus_give_number',
        //   // scopedSlots: { customRender: 'name' },
        // },
        {
          title: '可退金额',
          dataIndex: 'surplusMoney',

          scopedSlots: { customRender: 'surplusMoney' },
        },
        {
          title: '退出数量',
          dataIndex: 'returnBuyNumber',
          scopedSlots: { customRender: 'returnBuyNumber' },
        },
        // {
        //   title: '退出赠送数量',
        //   dataIndex: 'returnGiveNumber',

        //   scopedSlots: { customRender: 'returnGiveNumber' },
        // },
        {
          title: '退物品金额',
          dataIndex: 'returnMoney',

          scopedSlots: { customRender: 'returnMoney' },
        },
        {
          title: '是否退回仓库',
          dataIndex: 'is_return_warehouse',
          scopedSlots: { customRender: 'is_return_warehouse' },
        },
        {
          slots: { title: 'lossTitle' },
          dataIndex: 'lossMoney',
          scopedSlots: { customRender: 'lossMoney' },
        },
        {
          title: '是否退此订单',
          scopedSlots: { customRender: 'action' },
        },
      ],
      returnSumMoney: 0,
    }
  },
  created() {},
  methods: {
    studentInfos(e) {
      this.studentInfo = e
      this.form.student_id = e.id
      if(this.studentInfo.couserInfo.structures_ids==''){
        lookStructures({school_id:this.$store.state.user.school,type:1}).then(res=>{
          this.studentInfo.couserInfo.structures_ids=res
        }).catch(err=>{
          this.$message.error('校区获取失败')
        })
      }
      this.course_id=undefined
      this.structures_id=undefined
      this.isArrears=0
    },
    getReturnCourse() {
      
      this.courseList = []
      if (this.structures_id) {
        this.form.structures_id = this.structures_id
        studentGoods({ student_id: this.studentInfo.id, structures_id: this.structures_id })
          .then((res) => {
            this.courseList = res
          })
          .catch((err) => {
            this.$message.error(err.data.message || '获取物品失败')
          })
      }
    },
    getOrder() {
      if (this.course_id) {
        this.form.project_id = this.course_id
        this.courseList.forEach((item) => {
          if (item.type == 1) {
            this.isArrears = 1
            if (this.course_id === item.id) {
              this.orderArr = []
              this.orderArr = item.order
              this.orderArr.forEach((val) => {
                val.is_return_warehouse = 2
                val.buy_project = item.name
                val.project_type = item.project_type
              })
            }
          } else {
            if (this.course_id === item.id) {
              this.isArrears = 2
              this.orderArr = []

              this.orderArr = []
              this.orderArr = item.order
            }
          }
        })
        console.log(this.orderArr)
        this.returnSumMoney = 0
        this.orderArr.forEach((val) => {
          val.unit_price=(val.signing_price/val.buy_number).toFixed(2)
          val.returnBuyNumber = val.surplus_buy_number
          val.returnGiveNumber = val.surplus_give_number
          val.returnMoney = val.unit_price * val.surplus_buy_number
          val.out = true
          if (val.out) {
            this.returnSumMoney = this.returnSumMoney + val.returnMoney
          }
        })
      }
    },
    //退还购买课时 改变
    changeReturnBuyNumber(event, data, index) {
      console.log(event)
      console.log('退出购买课时', data)
      data.returnBuyNumber = event
      data.returnMoney = data.returnBuyNumber * data.unit_price
      data.serviceSumMoney = data.returnMoney
      data.serviceMoney = data.serviceSumMoney
      this.orderArr.splice(index, 1, data)
       this.returnSumMoney = 0
      this.orderArr.forEach((item) => {
        if (item.out) {
          this.returnSumMoney = this.returnSumMoney + item.returnMoney
        } 
      })
      // console.log(index)
    },
    changeReturnGiveNumber(event, data, index) {
      data.returnGiveNumber = event
      this.orderArr.splice(index, 1, data)
    },
    changeReturnMoney(event, data, index) {
      data.returnMoney = event
      data.serviceMoney = event
      console.log(data, '退出金额改变')
      this.orderArr.splice(index, 1, data)
       this.returnSumMoney = 0
      this.orderArr.forEach((item) => {
        if (item.out) {
          this.returnSumMoney = this.returnSumMoney + item.returnMoney
        } 
      })
    },
    returnWareHouse(e, data) {
      console.log(e.target.checked)
      if (e.target.checked) {
        data.is_return_warehouse = 1
      } else {
        data.is_return_warehouse = 2
      }
    },
    handerPayWay(item, index) {
      this.courrent = index
      this.form.refund_method = item.type
    },
    finishReturnCourse() {
      let params = JSON.parse(JSON.stringify(this.form))
      if (!params.student_id) {
        this.$message.warning('请选择退物品的学员!')
        return
      }
      if (!params.structures_id) {
        this.$message.warning('请选择校区')
        return
      }
      if (!params.project_id) {
        this.$message.warning('请选择物品订单!')
        return
      }
      this.orderArr.forEach((item) => {
        if (item.out) {
          params.order_arr.push({
            order_content_id: item.id,
            number: item.returnBuyNumber,
            give_number: item.returnGiveNumber,
            money: item.returnMoney,
            is_return_warehouse: item.is_return_warehouse,
          })
        }
      })
      if (params.order_arr == '') {
        this.$message.warning('请至少选择一份退物品的订单!')
        return
      }
      params.purchase_at = moment(this.$refs.otherInfo.todayDate).format('YYYY-MM-DD')
      params.remarks=this.$refs.otherInfo.remarks
      let that = this
      
      this.$confirm({
        title: '你确定要完成退物品吗？',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          createReturnCourse(params)
            .then((res) => {
              that.$message.success('退物品成功')
              that.$router.push({
                name: 'receipt',
                query: {
                  type: 'returnitem',
                  id: res.id,
                },
              })
            })
            .catch((err) => {
              that.$message.error(err.data.message || '退物品失败')
            })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    //查看订单
    openOrderModel(data) {
      this.$refs.orderModel.showModel(data)
    },
    remove(e, data, index) {
      if (e.target.checked) {
        data.out = true
      } else {
        data.out = false
      }
      this.orderArr.splice(index, 1, data)
      this.returnSumMoney = 0
      this.orderArr.forEach((item) => {
        if (item.out) {
          this.returnSumMoney = this.returnSumMoney + item.returnMoney
        } 
      })
      console.log(this.orderArr)
    },
    //补交
    afterPayMent(data) {
      this.$refs.afterPay.showModal(data)
    },
    update() {
      console.log('发送事件成功')
      this.courseList = []
      if (this.structures_id) {
        this.form.structures_id = this.structures_id
        studentGoods({ student_id: this.studentInfo.id, structures_id: this.structures_id })
          .then((res) => {
            this.courseList = res
            if (this.course_id) {
              this.form.project_id = this.course_id
              this.courseList.forEach((item) => {
                if (item.type == 1) {
                  this.isArrears = 1
                  if (this.course_id === item.id) {
                    this.orderArr = []
                    this.orderArr = item.order
                    this.orderArr.forEach((val) => {
                      val.is_return_warehouse = 2
                      val.buy_project = item.name
                      val.project_type = item.project_type
                    })
                  }
                } else {
                  if (this.course_id === item.id) {
                    this.isArrears = 2
                    this.orderArr = []

                    this.orderArr = []
                    this.orderArr = item.order
                  }
                }
              })
              this.returnSumMoney = 0
              this.orderArr.forEach((val) => {
                val.unit_price=(val.signing_price/val.buy_number).toFixed(2)
                val.returnBuyNumber = val.surplus_buy_number
                val.returnGiveNumber = val.surplus_give_number
                val.returnMoney = val.unit_price * val.surplus_buy_number
                this.returnSumMoney = this.returnSumMoney + val.returnMoney
                val.out = true
                if (val.out) {
                  this.returnSumMoney = this.returnSumMoney + val.returnMoney
                }
              })
            }
          })
          .catch((err) => {
            this.$message.error(err.data.message || '获取物品失败')
          })
      }
      this.$forceUpdate()
    },
  },
}
</script>

<style lang="less" scoped>
.mb10 {
  margin-bottom: 10px;
}
.title {
  margin-bottom: 8px;
  font-size: 16px;
  color: #333;
  font-weight: 700;
}
.empty-form {
  text-align: center;
}
.sum-money {
  line-height: 1;
  margin-left: 5px;
  font-size: 18px;
  color: #ff8534;
}
.headertitle {
  font-size: 16px;
  color: #333;
  line-height: 48px;
  font-weight: 500;
  border-bottom: 1px solid #e8e8e8;
}
.pay-way {
  .title {
    color: #333;
    margin-top: 13px;
    font-weight: 500;
    font-size: 14px;
    line-height: 20px;
    margin-bottom: 10px;
  }
  .refund-list {
    .active {
      border-color: rgb(255, 133, 52) !important;
    }
    .refund-item {
      cursor: pointer;
      display: inline-block;
      height: 40px;
      line-height: 40px;
      border-radius: 4px;
      border: 1px solid #d4d4d4;
      padding: 0 20px;
      color: #373737;
      margin-right: 10px;
      margin-top: 16px;
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 80px 10px 50px;
  margin: 0;
  box-shadow: 0 0 8px 0 #ccc;
  text-align: right;
  background: #fff;
  z-index: 16;
}
</style>